package com.fc.design.observer;

import java.util.ArrayList;
import java.util.List;

/**
 * <p> Author：lidongxu </p>
 * <p> Title：</p>
 * <p> Description：</p>
 * <p> Create Time：2020-04-07 16:05 </p>
 */
public class ObserverTest {
    public static void main(String[] args) {
        Subject subject = new ConcreteSubject();
        Observer obs1 = new ConcreteObserver1();
        Observer obs2 = new ConcreteObserver2();
        subject.add(obs1);
        subject.add(obs2);
        subject.notifyObserver();
    }
}

//具体目标
class ConcreteSubject extends Subject {
    public void notifyObserver() {
        System.out.println("具体目标发生改变...");
        System.out.println("--------------");

        for (Object obs : obervers) {
            ((Observer) obs).response();
        }

    }
}

abstract class Subject {
    protected List<Observer> obervers = new ArrayList<Observer>();

    public void add(Observer observer) {
        obervers.add(observer);
    }

    public void remove(Observer observer) {
        obervers.remove(observer);
    }

    public abstract void notifyObserver();
}

//抽象观察者
interface Observer {
    void response(); //反应
}

//具体观察者1
class ConcreteObserver1 implements Observer {
    public void response() {
        System.out.println("具体观察者1作出反应！");
    }
}

//具体观察者2
class ConcreteObserver2 implements Observer {
    public void response() {
        System.out.println("具体观察者2作出反应！");
    }
}